<template>
    <div class="news-news-detail g-padding-x" @click="closeMenu">
        <div class="news-news-detail-content">
            <div class="news-news-detail-nav">
                <a class="a_link" :href="`${hostPath}/news`">{{ $t('common.news') }}</a>
                <span class="text-[#9C9DB4]">/</span>
                <span class="text-[#9C9DB4] ellipsis">{{ article?.title }}</span>
            </div>
            <div class="mt-[24px] bg-cover">
                <img :src="article?.coverImg" :alt="article?.title" class="w-full" />
            </div>
            <div class="news-news-detail-title mt-[24px]">{{ article?.title }}</div>
            <p><span v-show="article?.author" class="text-[14px] text-[#3B3E55] pr-[4px]">{{
                article?.author }} ·</span>
                <span class="text-[14px] text-[#9C9DB4]">{{ dayjs(new
                    Date(article?.releaseTime).getTime()).format('YYYY-MM-DD') }}</span>
                <span class="text-[14px] text-[#9C9DB4] pl-[4px]">{{ $t('common.release') }}</span>
            </p>
            <div v-show="articleContent"
                class="container_warp dp-editor-md-preview-container blog dp-md-view overflow-auto min-h-[100px] blog-content-markdown">
                <div @click="handleClick" v-html="articleContent" />
            </div>
        </div>
        <!-- 目录 -->
        <Catalogue class="top-sticky" />
        <!-- 手机端目录 -->
        <Catalogue class="top-sticky-mobile" :style="{ display: menuOpen ? 'block' : 'none' }" />

    </div>
</template>
<script lang='ts' setup>
import { Message } from 'vue-devui/message'
import { useClipboard } from '@vueuse/core'
import { useNuxtApp, useAsyncData } from '#app'
import dayjs from 'dayjs'
import { metaConverter } from '@/utils/index'
import md from '@/utils/md'
import Catalogue from "./Catalogue/index.vue";
import allNewsData from '../Data/news.json'
import type { IResult } from './types/index'
import { useI18n } from 'vue-i18n';

const { t } = useI18n()
// 获取cookie里参数
const lan = useCookie('lang').value || 'zh';
let newsData = allNewsData[lan] || allNewsData.zh;
const hostPath = (import.meta as any).env.VITE_HOST
const { copy } = useClipboard()
const articleContent = ref('')
const router = useRouter()
const nuxtApp = useNuxtApp()
const serverDes = ref('')

const menuOpen = ref(false) //移动端的目录按钮


// 复制 详情中的代码
function handleClick(event: any) {
    const isCopyIcon = event.target.classList.contains('md-view-copy-icon')
    if (isCopyIcon) {
        let text = event.target?.previousElementSibling?.textContent || ''
        if (text.slice(-1) === '\n') {
            text = text.substring(0, text.length - 1)
        }
        copy(text)
        Message.success('复制成功')
    }
}
const article = ref<IResult>({
    releaseTime: '', id: '', path: '', title: '', desc: '', coverImg: '',author:''
})
// 查找文章的内容
async function getArticle() {

    const allData = Object.values(newsData).flat() // 获取所有的文章列表
    const id = router.currentRoute.value?.params.id as string
    article.value = allData.find((item: IResult) => item.id === id) as IResult
    const res = await useAsyncData('fileContent', () => nuxtApp.$readFile(article.value.path))
    const noLineResult = metaConverter(res.data.value as string) // 清除md头部的---
    const html = md.render(noLineResult)
    // xss过滤
    articleContent.value = handleHtmlString(html) // 转换成HTML并添加复制按钮

    // 获取描述
    const noTagData = html.replace(/<[^>]*>/g, '')
    const descContent = noTagData.split('\n').filter(item => item)
    if (article.value?.author) {
        descContent.unshift(article.value?.author)
    }
    if (article.value?.releaseTime) {
        descContent.unshift(article.value?.releaseTime)
    }
    serverDes.value = descContent.join(' ').substring(0, 200);
}

// 添加复制按钮
const codeCopyIcon = `<svg style="cursor: pointer;" class="icon md-view-copy-icon" aria-hidden="true" style="font-size:16px;display: inline-block;color:#3B3E55;"><use xlink:href="#gt-line-copy"></use></svg>`
function handleHtmlString(html: string) {
    try {
        const regex
            = /<pre([^>]*)>([\s\S]*?)<code([^>]*)>([\s\S]*?)<\/code>([\s\S]*?)<\/pre>/g

        return html.replace(
            regex,
            (
                match,
                preAttributes,
                preContent,
                codeAttributes,
                codeContent,
            ) => {
                // 在匹配的标签后面插入复制按钮，并保留样式
                return `<pre ${preAttributes}>${preContent}<code ${codeAttributes}>${codeContent}</code>${codeCopyIcon}</pre>`
            },
        )
    }
    catch {
        return html
    }
}

getArticle()

//移动端打开目录的方法
addEmitEvent('openMenu', ({ open }) => {
    menuOpen.value = open
})

function closeMenu() {
    menuOpen.value = false
    emitEvent('closeMenu', false)
}

useSeoMeta({
  charset: 'utf-8',
  title: () => `${article.value?.title} - ${t('common.tdk.gitcodeTitle')}`,
  ogTitle: () => `${article.value?.title} - ${t('common.tdk.gitcodeTitle')}`,
  description: () => serverDes.value,
  ogDescription: () => serverDes.value,
  keywords: () => article.value?.keywords || '',
  ogKeywords: () => article.value?.keywords || '',
})

</script>
<style lang='scss'>
@import '~/assets/css/devui_mdpreview.scss';

.dp-md-view {
    pre {
        position: relative;

        code {
            padding-right: 32px !important;
        }
    }

    .md-view-copy-icon {
        cursor: pointer;
        position: absolute;
        right: 8px;
        top: 9px;

        &:hover {
            opacity: 0.5;
        }
    }
}
</style>
<style scoped lang='scss'>
.news-news-detail {
    position: relative;
    max-width: 1200px;
    margin: 0 auto;
    margin-top: 32px;
    display: flex;
    justify-content: space-between;

    &-content {
        border: 1px solid #F1F1F8;
        padding: 16px;
        border-radius: 4px;
    }

    &-nav {
        font-size: 16px;
        color: #242536;
    }

    &-title {
        font-weight: 600;
        font-size: 24px;
        color: #242536;
        text-align: center;
    }

    img {
        border-radius: 4px;
        object-fit: cover;
    }

    .news-news-detail-content {
      flex: 1;
      overflow: hidden;
    }



    .bg-cover {

        width: 100%;

        img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }
}

.container_warp {
    min-height: 500px;
    padding-top: 24px;
    padding-bottom: 50px;
}

.top-sticky {
    position: sticky;
    top: 78px;
    flex: 1;
    margin-left: 20px;
    max-height: 420px;
    border: 1px solid #F1F1F8;
    overflow: hidden;
    border-radius: 4px;
    display: inline-block;
    height: max-content;
    flex: 0 0 300px;
}

.top-sticky-mobile {
    cursor: pointer;
    display: none;
    position: fixed !important;
    top: var(--header-height);
    right: 0;
    z-index: 10;
    max-width: 300px;
    flex: 0 0 300px;
    box-shadow: 0 1px 3px #1d1f3a0f, 0 2px 6px #1d1f3a0f, 0 4px 12px #1d1f3a0f, 0 8px 24px #1d1f3a0f;
}

.news-news-detail-nav {
    display: flex;
    align-items: center;
    gap: 4px;

    .a_link {

    }
}

.ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

@media screen and (max-width: 1024px) {
    .top-sticky {
        display: none;
    }

    .news-news-detail .news-news-detail-content {
        max-width: 100%;
        width: 100%;
    }

}
</style>
